import { useEffect, useState } from "react";

import { useFetch } from "../useFetch";

const Demo4 = () => {
  const [index, setIndex] = useState(1);

  const { data, loading, error } = useFetch(
    `https://pokeapi.co/api/v2/pokemon/${index}`
  );

  const handleClick = (key) => {
    if (key === "prev") {
      setIndex(index - 1);
    }
    if (key === "next") {
      setIndex(index + 1);
    }
  };

  const [uiLoading, setUiLoading] = useState(false);

  useEffect(() => {
    if (loading) {
      setUiLoading(true);
    } else {
      setTimeout(() => {
        setUiLoading(false);
      }, 500);
    }
  }, [loading]);

  const userDataView = () => {
    return (
      <>
        <div className="ProviderContainer BrownBorder">
          <section>
            <div className="content">
              <div>
                <button
                  className="link"
                  disabled={index === 1}
                  onClick={() => handleClick("prev")}
                >
                  Prev
                </button>
                <button className="link" onClick={() => handleClick("next")}>
                  Next
                </button>
              </div>
              <div className="contents">
                <div className="card">
                  <figure>
                    <img
                      className="img"
                      src={data?.sprites?.other?.dream_world?.front_default}
                      alt={data?.name}
                    />
                  </figure>
                </div>

                <div className="card">
                  <div className="half">
                    <img
                      src={data?.sprites?.other?.showdown?.front_default}
                      alt={data?.name}
                    />
                  </div>
                  <div className="half">
                    <img
                      src={data?.sprites?.other?.showdown?.back_default}
                      alt={data?.name}
                    />
                  </div>
                </div>
              </div>
              <div className="name">{data?.name}</div>
            </div>
            {uiLoading && (
              <div className="loading dots-loader">
                {/* <div className="loader" /> */}
                <span></span>
                <span></span>
                <span></span>
              </div>
            )}
          </section>
        </div>
      </>
    );
  };

  const errorView = () => {
    return (
      <>
        <h3>Error:</h3>
        <p>Message: {error.message}</p>
        <p>Documentation URL: {error.documentation_url}</p>
      </>
    );
  };

  if (error) return errorView();

  return userDataView();
};

export default Demo4;
